package com.example.chatrecommendation.controller;

import com.example.chatrecommendation.bean.dto.AgentAddDto;
import com.example.chatrecommendation.bean.dto.AgentDevDto;
import com.example.chatrecommendation.bean.dto.AgentUseDto;
import com.example.chatrecommendation.bean.dto.Messages;
import com.example.chatrecommendation.bean.entity.Agent;
import com.example.chatrecommendation.service.AgentService;
import com.example.chatrecommendation.service.ChattingRecordsService;
import com.example.chatrecommendation.tool.Api;
import com.example.chatrecommendation.tool.R;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jasmine-drs
 * @date 2024/5/19 11:08
 */

@Slf4j
@RestController
@RequestMapping("/agents")
public class AgentController {

	private final AgentService agentService;
	private final ChattingRecordsService chattingRecordsService;
	private final Api API;

	public AgentController(AgentService agentService, ChattingRecordsService chattingRecordsService, Api api) {
		this.agentService = agentService;
		this.chattingRecordsService = chattingRecordsService;
		API = api;
	}

	/**
	 * 获取智能体列表
	 * 通过账号，不是id获取
	 *
	 * @param studentAccount 学生账号
	 * @return 智能体列表
	 */
	@GetMapping("/getAgents")
	@ApiOperation("获取智能体列表")
	public R<List<Agent>> getAgents(@RequestParam Integer studentAccount) {
		return R.success(agentService.getAgents(studentAccount));
	}

	/**
	 * 新增智能体
	 *
	 * @param addDto 用户描述信息，还包括头像id
	 * @return 智能体配置信息
	 */
	@PostMapping("/addAgent")
	@ApiOperation("新增智能体")
	public R<Agent> addAgent(@RequestBody AgentAddDto addDto) throws MalformedURLException {
		return R.success(agentService.addAgent(addDto));
	}

	/**
	 * 修改配置
	 *
	 * @param agent 智能体配置
	 * @return 修改结果
	 */
	@PutMapping("/updateAgent")
	@ApiOperation("修改智能体配置")
	public R<String> updateAgent(@RequestBody Agent agent) {
		agentService.updateById(agent);
		return R.success("修改成功");
	}

	/**
	 * 使用智能体进行问答
	 *
	 * @param agentUseDto 聊天信息
	 * @return 回答内容
	 */
	@PostMapping("/useAgent")
	@ApiOperation("使用智能体进行问答")
	public R<String> useAgent(@RequestBody AgentUseDto agentUseDto) throws MalformedURLException {
//		SseEmitter emitter = new SseEmitter();
//		ExecutorService executor = Executors.newSingleThreadExecutor();
//		String jsonInputString = String.format("{\"model\": \"qwen-turbo\", \"input\": {\"messages\": [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}, {\"role\": \"user\", \"content\": \"%s\"}]}, \"parameters\": {\"result_format\": \"message\",\"incremental_output\":true}}", agentUseDto.getMessage());
//
//		String regex = "\"content\":\"(.*?)\",\"role\"";
//		Pattern pattern = Pattern.compile(regex);
//		executor.execute(() -> {
//
//			HttpURLConnection connection = null;
//			try {
//				URL url = new URL(URL_STR);
//				connection = (HttpURLConnection) url.openConnection();
//
//				connection.setRequestMethod("POST");
//				connection.setRequestProperty("Content-Type", "application/json");
//				connection.setRequestProperty("Authorization", "Bearer " + API_KEY);
//				connection.setRequestProperty("X-DashScope-SSE", "enable");
//				connection.setDoOutput(true);
//
//				try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
//					wr.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
//					wr.flush();
//				}
//
//				try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
//					String inputLine;
//					while ((inputLine = in.readLine()) != null) {
//						Matcher matcher = pattern.matcher(inputLine);
//						if (matcher.find()) {
//							String content = matcher.group(1);
//							emitter.send(content); // 实时发送数据给客户端
//						}
//					}
//				}
//				emitter.complete(); // 完成发送
//			} catch (Exception e) {
//				e.printStackTrace();
//				emitter.completeWithError(e); // 发生错误时发送错误信号
//			} finally {
//				if (connection != null) {
//					connection.disconnect();
//				}
//				executor.shutdown();
//			}
//		});
		System.out.println("agentUseDto = " + agentUseDto);
		List<Messages> message = agentUseDto.getMessage();
		message.get(0).setContent("现在你是一个智能体，请根据智能体的名称、描述和配置进行回答。\\n名称：" +
				agentUseDto.getName() + "\\n描述：" + agentUseDto.getDescription() + "\\n配置：" + agentUseDto.getConfig());
		String result = API.callLargeModel(message);
		result = result.replace("\\n", "<br>");

		List<Messages> list = new ArrayList<>();
//		找到最新的用户提问
		Messages messages = agentUseDto.getMessage().get(agentUseDto.getMessage().size() - 1);
//		构建最新的对话
		list.add(new Messages(messages.getRole(), messages.getContent()));
		list.add(new Messages("assistant", result));
//		保存历史记录到数据库
		chattingRecordsService.saveChatRecords(agentUseDto.getChattingId(), list);
		return R.success(result);
	}

	/**
	 * 删除智能体
	 *
	 * @param id 智能体id
	 * @return 删除结果
	 */
	@DeleteMapping("/deleteAgent")
	@ApiOperation("删除智能体")
	public R<String> deleteAgent(@RequestParam Integer id) {
		agentService.removeById(id);
		return R.success("删除成功");
	}

	/**
	 * 调试智能体
	 *
	 * @param agentDevDto 智能体数据
	 * @return 回答
	 */
	@PostMapping("/dev")
	@ApiOperation("调试智能体")
	public R<String> dev(@RequestBody AgentDevDto agentDevDto) throws MalformedURLException {
		List<Messages> message = agentDevDto.getMessage();
		message.get(0).setContent("现在你是一个智能体，请根据智能体的名称、描述和配置进行回答。\\n名称：" +
				agentDevDto.getName() + "\\n描述：" + agentDevDto.getDescription() + "\\n配置：" + agentDevDto.getConfig());
		String result = API.callLargeModel(message);
		message.add(new Messages("assistant", result));
//		调试记录不保存到数据库
		return R.success(result);
	}
}
